﻿using HslCommunication;
using HslCommunication.MQTT;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace S7Project_One.Base
{
    public class MQTT
    {
        public static MqttServer mqttServer;
        public static MqttClient mqttClient;
        public static void CreateMqttServer(int port)
        {
            mqttServer = new MqttServer();
            mqttServer.ServerStart(port);
            Task.Run(() =>
            {
                Debug.WriteLine("启动CreateMqttServer完成");
                int tick = 0;
                while (true)
                {
                    Thread.Sleep(1000);
                    // 每秒以字符串的形式推送一个数据给订阅的客户端，1,2,3,4,5,6,7,...
                    mqttServer.PublishTopicPayload("A", Encoding.UTF8.GetBytes(tick.ToString()));
                    tick++;   // 让数据变化，方便查看
                }
            });

        }
        public static void CreateMqttClient(int port)
        {
            try
            {

                mqttClient = new MqttClient(new MqttConnectionOptions()
                {
                    IpAddress = "127.0.0.1",
                    Port = port,
                    //Credentials = new MqttCredential("admin", "123456"),  // 增加用户名密码确认
                    //UseRSAProvider = true,                                // 通信加密
                });
                mqttClient.OnMqttMessageReceived += MqttClient_OnMqttMessageReceived;  // 绑定事件显示
                OperateResult connect = mqttClient.ConnectServer();

                if (!connect.IsSuccess)
                {
                    Console.WriteLine("Connect failed: " + connect.Message);
                    MessageBox.Show("client error " + connect.Message);
                    return;
                }
                // 订阅
                mqttClient.SubscribeMessage("A");

            }
            catch (Exception ex)
            {
                MessageBox.Show("Clent Error " +ex.Message);
                return;
            }

        }
        private static void MqttClient_OnMqttMessageReceived(MqttClient client, MqttApplicationMessage message)
        {
            string topic = message.Topic;
            byte[] payload = message.Payload;

            // 接收到服务器发送的数据触发的事件，这里就是先显示下
            Debug.WriteLine(DateTime.Now.ToString() + $" Topic[{topic}] {Encoding.UTF8.GetString(payload)}");

        }
    }
}
